package com.tanhua.mongo.service;

/**
 * @Author: cl
 * @Date: 2022/5/4 - 05 - 04
 * @Description:
 */

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 异步处理工具类(1、启动类加注解@EnableAsync，2、需要开启线程方法上加注解@Async)
 */
@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Long userId, ObjectId movementId) {
        //2、查询朋友关系(好友id)
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //3、保存到时间表线数据表(循环查询朋友的id)(因为数据太多，用异步，可以开启新的线程)
        if (!CollUtil.isEmpty(friends)) {
            for (Friend friend : friends) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movementId);
                movementTimeLine.setUserId(friend.getUserId());
                movementTimeLine.setFriendId(friend.getFriendId());
                movementTimeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.save(movementTimeLine);
            }
        }
    }
}
